#!/bin/bash

## %CopyrightBegin%
## 
## SPDX-License-Identifier: Apache-2.0
##
## Copyright Ericsson AB 2017-2025. All Rights Reserved.
##
## Licensed under the Apache License, Version 2.0 (the "License");
## you may not use this file except in compliance with the License.
## You may obtain a copy of the License at
##
##     http://www.apache.org/licenses/LICENSE-2.0
##
## Unless required by applicable law or agreed to in writing, software
## distributed under the License is distributed on an "AS IS" BASIS,
## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
## See the License for the specific language governing permissions and
## limitations under the License.
##
## %CopyrightEnd%

set -e

filter () {
    FILTER_RESULT=""
    for app in $1; do
        if echo " $2 " | grep -v " $app " > /dev/null; then
            FILTER_RESULT="$FILTER_RESULT $app"
        fi
    done
}

if [ "X$ERL_TOP" != "X" ] && [ -d $ERL_TOP/lib ]; then
    LIB_DIR=$ERL_TOP/lib
else
    LIB_DIR=$(erl -noshell -eval 'io:format("~ts~n",[code:lib_dir()])' -s init stop)
fi
ALL_APPLICATIONS=$(ls -d -1 $LIB_DIR/*/ | sed "s:^$LIB_DIR/::g" | sed "s:/$::g")
ALL_APPLICATIONS="erts $ALL_APPLICATIONS"
echo "All applications: $ALL_APPLICATIONS" |tr '\n' ' ' && echo ""

BASE_PLT="compiler crypto erts kernel stdlib syntax_tools"
APP_PLT="asn1 debugger edoc et ftp inets mnesia observer parsetools public_key sasl runtime_tools snmp ssl tftp wx xmerl tools"
NO_UNMATCHED="common_test eunit inets megaco mnesia snmp ssh ssl observer reltool"
WARNINGS="diameter"

filter "$ALL_APPLICATIONS" "$NO_UNMATCHED $WARNINGS $TRAVIS_SKIP"
UNMATCHED=$FILTER_RESULT
filter "$APP_PLT" "$TRAVIS_SKIP"
APP_PLT=$FILTER_RESULT
filter "$NO_UNMATCHED" "$TRAVIS_SKIP"
NO_UNMATCHED=$FILTER_RESULT
filter "$WARNINGS" "$TRAVIS_SKIP"
WARNINGS=$FILTER_RESULT

echo "UNMATCHED = $UNMATCHED"
echo "NO_UNMATCHED = $NO_UNMATCHED"
echo "WARNINGS = $WARNINGS"

DIALYZER=dialyzer

if [ -f $ERL_TOP/bin/dialyzer ]; then
    DIALYZER=$ERL_TOP/bin/dialyzer
fi

PLT="$(mktemp).plt"

set -x

$DIALYZER --build_plt --output_plt "$PLT" -Wunknown -Woverlapping_contract -Wopaque_union --apps $BASE_PLT $APP_PLT --statistics
$DIALYZER -n --plt "$PLT" -Wunknown -Wunmatched_returns -Woverlapping_contract -Wopaque_union --apps $UNMATCHED --statistics
$DIALYZER -n --plt "$PLT" -Wunknown -Woverlapping_contract -Wopaque_union --apps $NO_UNMATCHED --statistics
if [ "X$WARNINGS" != "X" ]; then
    $DIALYZER -n --plt "$PLT" --apps $WARNINGS --statistics || true
fi
